package com.tarena.lbs.attach.service.impl;

import com.alibaba.fastjson2.JSON;
import com.google.zxing.WriterException;
import com.tarena.lbs.attach.dao.mapper.AttachMapper;
import com.tarena.lbs.attach.dao.repository.AttachRepository;
import com.tarena.lbs.attach.enums.AttachResultEnum;
import com.tarena.lbs.attach.enums.FileTypeEnum;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.param.AttachQRParam;
import com.tarena.lbs.attach.pojo.param.AttachUpdateParam;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.po.AttachPO;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.attach.pojo.vo.FileVO;
import com.tarena.lbs.attach.service.AttachService;
import com.tarena.lbs.attach.utils.FileUtil;
import com.tarena.lbs.attach.utils.QRCodeUtil;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Service
@Slf4j
public class AttachServiceImpl implements AttachService {

    @Value("${image_path}")
    private String imagePath;

    @Value("${url}")
    private String url;

    @Autowired
    private AttachRepository attachRepository;

    @Override
    public boolean batchUpdateBusiness(List<PicUpdateParam> params) {
        return attachRepository.batchUpdateBusiness(params);
    }

    @Override
    public List<AttachDTO> getAttachInfo(AttachQuery attachQuery) {
        List<AttachPO> attachPOList = attachRepository.getAttachInfo(attachQuery);
        List<AttachDTO> attachDTOList = new ArrayList<>();
        if (attachPOList != null && !attachPOList.isEmpty()) {
            for (AttachPO attachPO : attachPOList) {
                AttachDTO attachDTO = convertAttachPOToDTO(attachPO);
                attachDTOList.add(attachDTO);
            }
        }
        return attachDTOList;
    }

    @Override
    public List<AttachDTO> batchGetAttachInfo(List<Integer> idList, Integer type) {
        List<AttachPO> attachPOList = attachRepository.batchGetAttachInfo(idList, type);
        List<AttachDTO> attachDTOList = new ArrayList<>();
        if (attachPOList != null && !attachPOList.isEmpty()) {
            for (AttachPO attachPO : attachPOList) {
                AttachDTO attachDTO = convertAttachPOToDTO(attachPO);
                attachDTOList.add(attachDTO);
            }
        }
        return attachDTOList;
    }

    @Override
    public int batchUpdateAttachByIdList(List<AttachUpdateParam> attachUpdateParamList) {
        return 0;
    }

    @Override
    public int deleteAttachByBusinessIdAndBusinessType(AttachUpdateParam attachUpdateParam) {
        return attachRepository.deleteAttachByBusinessIdAndBusinessType(attachUpdateParam);
    }

    @Override
    public int deleteAttachById(Long id) {
        return attachRepository.deleteAttachById(id);
    }

    @Override
    public int deleteAttachInfoByParam(AttachQuery attachQuery) {
        return attachRepository.deleteAttachInfoByParam(attachQuery);
    }

    @Override
    public AttachDTO generateQrCode(AttachQRParam attachQRParam) {
        String fileUuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(Locale.ROOT);
        QRCodeUtil.createCodeToFile(attachQRParam.getContent(), new File(imagePath), fileUuid + ".png");
        //存储图片
        //TODO: 不知道需不需要储数据库
        AttachPO attachPO = new AttachPO();
        attachPO.setFileUuid(fileUuid + ".png");
        attachPO.setClientFileName(fileUuid + ".png");
        attachPO.setContentType(FileTypeEnum.PICTURE.getType());
        long currentTime = System.currentTimeMillis();
        attachPO.setGmtCreate(currentTime);
        attachPO.setGmtModified(currentTime);
        attachPO.setBusinessId(attachQRParam.getBusinessId());
        attachPO.setBusinessType(attachQRParam.getBusinessType());
        // 保存到数据库
        attachRepository.insert(attachPO);

        // 转换为 AttachDTO 并返回
        return convertAttachPOToDTO(attachPO);
    }

    @Override
    public AttachDTO insertAttachInfo(MultipartFile file, String fileUuid) {
        AttachPO attachPO = new AttachPO();
        attachPO.setFileUuid(fileUuid);
        attachPO.setClientFileName(file.getOriginalFilename());
        attachPO.setContentLength(file.getSize());
        String contentType = file.getContentType();
        if (contentType != null) {
            if (contentType.startsWith("image")) {
                attachPO.setContentType(FileTypeEnum.PICTURE.getType()); // 图片类型
            } else if (contentType.startsWith("video")) {
                attachPO.setContentType(FileTypeEnum.VIDEO.getType()); // 视频类型
            } else {
                attachPO.setContentType(FileTypeEnum.UNKNOWN.getType()); // 未知类型
            }
        } else {
            attachPO.setContentType(FileTypeEnum.UNKNOWN.getType());
        }

        // 设置时间戳
        long currentTime = System.currentTimeMillis();
        attachPO.setGmtCreate(currentTime);
        attachPO.setGmtModified(currentTime);

        // 保存到数据库
        attachRepository.insert(attachPO);

        // 转换为 AttachDTO 并返回
        return convertAttachPOToDTO(attachPO);
    }

    private AttachDTO convertAttachPOToDTO(AttachPO attachPO) {
        AttachDTO attachDTO = new AttachDTO();
        BeanUtils.copyProperties(attachPO, attachDTO);
        if (attachPO.getContentLength() != null) {
            attachDTO.setContentLength(attachPO.getContentLength().intValue());
        }
        // 设置 contentType 显示名称
        if (attachPO.getContentType() != null) {
            switch (attachPO.getContentType()) {
                case 1:
                    attachDTO.setContentType(FileTypeEnum.PICTURE.getMessage());
                    break;
                case 2:
                    attachDTO.setContentType(FileTypeEnum.VIDEO.getMessage());
                    break;
                default:
                    attachDTO.setContentType(FileTypeEnum.UNKNOWN.getMessage());
                    break;
            }
        }
        return attachDTO;
    }
}
